package common

import (
	"errors"
	"fmt"
	"gitee.com/dingyangzhuang/dingutils/dlog/logger"
	"gitee.com/dingyangzhuang/dingutils/ip"
	expect "github.com/google/goexpect"
	"golang.org/x/crypto/ssh"
	"strings"
)

func ExecuteDefineCmd(addr string, port string, user string, passwd string, argumentMap map[string]interface{},
	defineFunc func(*expect.GExpect, map[string]interface{}, string) error) (string, error) {
	sshClt, err := ssh.Dial("tcp", addr+":"+port, &ssh.ClientConfig{
		User:            user,
		Auth:            []ssh.AuthMethod{ssh.Password(passwd)},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		Timeout:         TIMEOUT,
	})
	bool := ip.Isping(addr)
	if !bool {
		logger.Error("%q 连通性异常 ", addr)
		return "", errors.New(fmt.Sprintf("%q 连通性异常", addr))
	}
	if err != nil {
		logger.Error("ssh.Dial(%q) failed: %v", addr, err)
		return "", errors.New(fmt.Sprintf("ssh.Dial(%q) failed: %v", addr, err))
	}
	//最后关闭ssh
	defer sshClt.Close()

	e, _, err := expect.SpawnSSH(sshClt, TIMEOUT)
	if err != nil {
		logger.Error(err.Error())
		return "", errors.New(fmt.Sprintf("%q failed 登录失败: %v", addr, err))
	}
	defer e.Close()

	_, _, err = e.Expect(userReg, TIMEOUT)
	if err != nil {
		logger.Error("%s 开始匹配失败:%s", addr, err.Error())
		return "", errors.New(fmt.Sprintf("%s 开始匹配失败:%s", addr, err.Error()))
	}
	_, err = sendRootMsg(e, "sudo -i")
	if err != nil {
		logger.Error("%s sudo 失败:%s", addr, err.Error())
		return "", errors.New(fmt.Sprintf("%s sudo 失败1111111111:%s", addr, err.Error()))
	}
	msg, err := sendRootMsg(e, "whoami")
	if err != nil {
		logger.Error("%s 执行whoami失败:%s", addr, err.Error())
		return "", errors.New(fmt.Sprintf("%s 执行whoami失败:%s", addr, err.Error()))
	}
	if msg == "root" || strings.Contains(msg, "root") {

		err := defineFunc(e, argumentMap, addr)
		if err != nil {
			return "", errors.New(fmt.Sprintf("%s 执行自定义命令失败:%s", addr, err.Error()))
		}

	}
	return "执行成功", nil
}
